<script setup lang="ts">
import * as monaco from 'monaco-editor'
import {nextTick, onMounted, ref, watch} from 'vue'


// 容器对象
const editorContainer = ref()

// 编辑器对象
let codeEditor: monaco.editor.IStandaloneCodeEditor | null = null

// 声明一个input事件
const emit = defineEmits(['update:modelValue'])

// 从父组件中接收
const props = defineProps({
  language: {
    type: String,
    default: 'sql'
  },
  modelValue: {
    type: String,
    default: '',
  },
  height: {
    type: [String, Number],
    default: '100%'
  },
  minHeight: {
    type: [String, Number],
    default: '200px'
  },
  width:  {
    type: [String, Number],
    default: '100%'
  },
})

onMounted(() => {
  nextTick(()=>{
    codeEditor = monaco.editor.create(editorContainer.value, {
      value: props.modelValue,
      language: props.language,
      lineNumbers: "on",
      roundedSelection: false,
      scrollBeyondLastLine: false,
      readOnly: false,
      theme: 'vs-dark',
      fontSize: 14
    })

    // 设置监听事件
    codeEditor.onDidChangeModelContent(() => {
      emit('update:modelValue', codeEditor?.getValue())
    })
  })
})

// 监听 modelValue 的变化，确保编辑器的值与 prop 保持同步
watch(() => props.modelValue, (newValue) => {
  if (codeEditor && newValue !== codeEditor.getValue()) {
    codeEditor.setValue(newValue || '')
  }
})
</script>

<template>
  <div ref="editorContainer" :style="{height, width, minHeight}"/>
</template>

<style scoped>

</style>
